#include <SD.h>
#include <TMRpcm.h>
#include <SPI.h>



TMRpcm tmrpcm;


int btnPin = 2;
int laBaPin = 9;
int knobPin = A0;
int sdPin = 10;


int btnPinFlg = 0;
int knobPinNum = 0;

void setup() {
    // put your setup code here, to run once:
    
    Serial.begin(9600);
    Serial.println("*** start ***");
    initPin();
}

// ---------------------------------------------------------------------
void loop() {

    int btnPinRead = digitalRead(btnPin);
    if(btnPinRead > 0) {
      while(btnPinRead = digitalRead(btnPin)) {}
      pauseMusic();
    }

    char c = Serial.read();
    switch(c) {
      case 'k':
        decMusicVolume();
        break;
      case 'j':
        incMusicVolume();
        break;
      case 'p':
        playMusic("1.wav");
        break;
      case 's':
        stopPlayMusic();
        break;

    }

    knobPinNum = analogRead(knobPin);
    if(knobPinNum < 340) {
      tmrpcm.setVolume(3);
    }else if(knobPinNum > 340 && knobPinNum < 680) {
      tmrpcm.setVolume(4);
    }else {
      tmrpcm.setVolume(5);
    }
    

    delay(50);

}

// ---------------------------------------------------------------------

void initPin() {
    
    pinMode(btnPin, INPUT);
    pinMode(knobPin, INPUT);


    tmrpcm.speakerPin = laBaPin;
    tmrpcm.quality(true);
    // tmrpcm.setVolume(5);

    if (!SD.begin(sdPin)) {
        Serial.println("SD fail");  
    } else {   
        Serial.println("SD ok");   
    }

}

void playMusic(char* music) {
  tmrpcm.play(music);
}

void pauseMusic() {
  tmrpcm.pause();
}

void stopPlayMusic() {
  tmrpcm.stopPlayback();
}


void decMusicVolume() {
  tmrpcm.volume(0);
}

void incMusicVolume() {
  tmrpcm.volume(1);
}











